package cn.yusei.teamTribe.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.yusei.teamTribe.constant.MessageType;
import cn.yusei.teamTribe.dao.JedisDAO;
import cn.yusei.teamTribe.entity.Message;
import cn.yusei.teamTribe.util.JedisKeyUtil;

@Service
public class MessageService {

	@Autowired
	private JedisDAO jedisDAO;
	
	private static final char MESSAGE_SPLIT = '|';
	private static final char MESSAGE_INNER_SPLIT = '_';
	
	private String getKey(int id, int type)
	{
		String key = null;
		switch(type)
		{
			case MessageType.RELATION_REQUEST : key = JedisKeyUtil.UNREAD_RELATION_REQUEST + id; break ;
			case MessageType.RELATION_RESPONSE : key = JedisKeyUtil.UNREAD_RELATION_RESPONSE + id; break ;
			case MessageType.TEAM_MEMBER_REQUEST : key = JedisKeyUtil.UNREAD_TEAM_MEMBER_REQUEST + id; break;
			case MessageType.TEAM_MEMBER_RESPONSE : key = JedisKeyUtil.UNREAD_TEAM_MEMBER_RESPONSE + id; break;
			default : throw new IllegalArgumentException("消息种类 [" + "type" + "] 不存在");
		}
		return key;
	}
	
	private void appendToEnd(String key, String value, String newItem)
	{
		jedisDAO.set(key, value + (value.equals("") ? "" : MESSAGE_SPLIT) + newItem);
	}
	
	/**
	 * 
	 * @param id 消息接受者id
	 * @param type
	 * @param requestId 消息的 id
	 */
	public void addMessage(int id, int type, long requestId)
	{
		String key = getKey(id, type);
		String message = jedisDAO.get(key);
		if(message == null)
			message = "";
		appendToEnd(key, message, "" + requestId + MESSAGE_INNER_SPLIT + type);   ///最前面的 "" 不能去掉
	}
	
	public List<Message> getMessage(int id, int type)
	{
		List<Message> messages = new ArrayList<Message>();
		String key = getKey(id, type);
		String value = jedisDAO.get(key);
		if(value != null)
		{
			String[] strs = value.split("\\" + MESSAGE_SPLIT);
			for(String str : strs)
			{
				String[] num = str.split("" + MESSAGE_INNER_SPLIT);
				Message message = new Message();
				message.setId(Integer.valueOf(num[0]));
				message.setType(Integer.valueOf(num[1]));
				messages.add(message);
			}
		}
		jedisDAO.del(key);
		return messages;
	}
	
}
